package test.service;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import test.domain.Organization;
import test.domain.User;
import test.repository.OrganizationRepository;
import test.repository.UserRepository;

@Service
public class BootstrapService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrganizationRepository organizationRepository;

    @Autowired
    private PlatformTransactionManager tm;

    @PostConstruct
    public void prepareData() {
        new TransactionTemplate(tm).execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                Organization organization = new Organization("Bank Of America");

                organization = organizationRepository.save(organization);

                for (int i = 0; i < 10; i++) {
                    User user = userRepository.save(new User("User" + i, organization));

                    user.setSalary(1000 + 10 * i);
                    user.setPosition( (i % 2 == 0) ? "manager" : "developer");
                }
            }
        });
    }
}
